import os
import pandas as pd
from scipy.linalg import norm


# 输入为要比较的两个文本的id（在数据集中的行数-1）
# 基于tfidf的余弦相似度：比较文本之间的相似程度
def cosine_similarity(id1: int, id2: int) -> float:
    tfidf_file = 'tfidf.csv'
    if not os.path.exists(tfidf_file):
        raise ValueError("input file: {} doesn't not exist".format(tfidf_file))
    tfidfs = pd.read_csv(tfidf_file, encoding='utf8')
    result = 0
    list1 = list(tfidfs.iloc()[id1])
    list2 = list(tfidfs.iloc()[id2])
    for i in range(len(list1)):
        result += list1[i] * list2[i]
    try:
        result = result/(norm(list1) * norm(list2))  # norm()求范数，默认为二范数
    except ZeroDivisionError:
        result = 0
    return result
